import { createRouter, createWebHistory } from 'vue-router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import db from '@/store/localstorage';
import request from '@/config/request';
import utils from '@/utils/utils';
const routeAllPathToCompMap = import.meta.glob(`@/views/*.vue`);
const viewComponents = import.meta.glob(`@/views/**/*.vue`);
NProgress.configure({ showSpinner: false });

//动态路由
let menuList: any = [];
let isAddDynamicMenuRoutes = false;
//初始化路由
const CommonRoute = [
	{ path: '/', redirect: '/login' },
	{
		path: '/login',
		name: '管理员登录',
		component: () => import('@/views/login/index.vue')
	}
];

const router = createRouter({
	history: createWebHistory(),
	routes: CommonRoute
});

/**
 * 免登录白名单
 * @type {string[]}
 */
const whiteList = ['/login'];

router.beforeEach((to, from, next) => {
	let toToken = to.query.token;
	if (toToken != undefined) {
		request
			.get('/dataview/login/tokenLogin', { token: toToken })
			.then(ret => {
				// db.save('ROLES', val);
				let data = ret.data;
				db.save('USER_TOKEN', data.token);
				db.save('USER', data);
				db.save('PERMISSIONS', data.role);
				db.save('ROLES', data.menu);
				next('/data/map');
			})
			.catch(err => {
				db.clear();
				next('/login');
				return;
			});
		return;
	}
	NProgress.start();
	//白名单内
	if (whiteList.indexOf(to.path) >= 0) {
		next();
		return;
	}
	let token = db.get('USER_TOKEN');
	let user = db.get('USER');
	let userRouter = db.get('ROLES');
	//没有登录的情况下
	if (!token.length || !user || !userRouter.length) {
		next('/login');
	}
	//判断路由是否存在
	if (isAddDynamicMenuRoutes == false) {
		let hanleList = hanleFor(userRouter);
		hanleList.forEach((value: any) => {
			if (value) {
				router.addRoute(value);
			}
		});
		//添加404路由
		router.addRoute({
			name: 'NotFont',
			path: '/:pathMatch(.*)*',
			alias: '/404',
			component: () => import('@/views/404.vue')
		});
		isAddDynamicMenuRoutes = true;
		next({ ...to, replace: true });
	} else {
		next();
	}
});

router.afterEach(() => {
	NProgress.done();
});

function hanleFor(list: any) {
	for (let i = 0; i < list.length; i++) {
		if (list[i].children && list[i].children != null && list[i].menuNum > 0) {
			hanleFor(list[i].children);
		} else {
			let res = createRoute(list[i]);
			menuList.push(res);
		}
	}
	return menuList;
}

function createRoute(menu: any) {
	if (menu.authorize == null || menu.authorize == undefined || menu.authorize == '') {
		return;
	}
	// 获取页面按钮
	let buttons: any = [];
	if (menu.children && menu.children.length > 0 && menu.btnNum > 0) {
		menu.children.forEach((x: any) => {
			if (x.isButton == 1 && x.isShow == true) {
				buttons.push(x);
			}
		});
	}
	menu.buttons = buttons;
	let childComponent = viewComponents[`/src/views/${menu.url}.vue`];
	if (utils.isEmpty(childComponent)) {
		childComponent = viewComponents[`/src/views/404.vue`];
	}
	return {
		path: '/' + menu.url,
		meta: { name: menu.name, buttons: menu.buttons },
		component: routeAllPathToCompMap[`/src/views/layout.vue`],
		children: [
			{
				path: '',
				meta: { id: menu.menuId, name: menu.name, url: menu.url, buttons: menu.buttons },
				component: childComponent
			}
		]
	};
}

export default router;
